#include"Acceptor.h"
#include"Socket.h"
#include"channel.h"
#include"sever.h"
#include<iostream>

Acceptor::Acceptor(/* args */)
{
}

Acceptor::Acceptor(EventLoop *_loop):loop(_loop)
{
        //服务器端口信息
    InetAddress *addr = new InetAddress(INADDR_ANY,8889);
    socket = new Socket();
    socket->Bind(addr);
    socket->Listen();
    socket->setNotBolcking();
    std::cout<<"开始监听"<<std::endl;
    

    //服务器通道处理
    accCh = new MyChannel(loop,socket->getFd());
    std::function<void()> cb = std::bind(&Acceptor::acceptConnection,this);
    accCh->setReadCallBack(cb);
    accCh->enableReading();

    delete addr;
}

Acceptor::~Acceptor()
{
    delete socket;
    delete accCh;
}
//接受客户端新的连接
void Acceptor::acceptConnection()
{
    InetAddress* clnt_addr = new InetAddress();
    Socket* clnt_sock = new Socket(socket->Accept(clnt_addr));
    std::cout << "ip:\t" << clnt_addr->getIp() << "\tport:\t" << clnt_addr->getPort() << std::endl;
    clnt_sock->setNotBolcking();
    newConnectionCallback(clnt_sock);
    delete clnt_addr;
}

void Acceptor::setNewConnectionCallBack(std::function<void(Socket *)> soc)
{
    newConnectionCallback = soc;
}
